package com.sunchangpeng.wechat.core.http;

import com.sunchangpeng.wechat.core.exception.WechatClientException;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.Map;

import static com.sunchangpeng.wechat.core.http.HttpMediaType.*;

@Slf4j
public class HttpClient {
    private final OkHttpClient httpClient;

    public HttpClient(OkHttpClient httpClient) {
        this.httpClient = httpClient;
    }

    public HttpResponseWrapper http(String url, String json) {
        if (StringUtils.isNotBlank(json)) {
            return doExecute(new Request.Builder()
                    .url(url)
                    .post(RequestBody.create(APPLICATION_JSON_UTF8, json))
                    .build());
        }

        return doExecute(new Request.Builder()
                .url(url)
                .build());
    }

    public HttpResponseWrapper http(String url, String name, String fileName, byte[] content, Map<String, String> form) {
        MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder()
                .addFormDataPart(name, fileName, RequestBody.create(APPLICATION_OCTET_STREAM, content))
                .setType(MULTIPART_FORM_DATA);

        if (form != null && !form.isEmpty()) {
            for (String key : form.keySet()) {
                multipartBodyBuilder.addFormDataPart(key, form.get(key));
            }
        }

        return doExecute(new Request.Builder()
                .url(url)
                .post(multipartBodyBuilder.build())
                .build());
    }

    private HttpResponseWrapper doExecute(Request request) {
        try {
            return HttpResponseWrapper.of(httpClient.newCall(request).execute());
        } catch (IOException e) {
            throw new WechatClientException("I/O error on " + request, e);
        }
    }
}
